<template>
  <div class="common-tree comp-depts" v-loading.fullscreen="loading">
    <div class="common-tree__nect" v-show="$slots.head || $scopedSlots.head">
      <slot
        name="head"
        :loading="loading"
        :filters="filters"
        :selects="selects"
      ></slot>
    </div>
    <div class="common-tree__body" ref="scroller">
      <div class="item item--lv0">
        <div class="name">部门名称</div>
        <div class="space" v-show="$slots.body || $scopedSlots.body">操作</div>
      </div>
      <el-tree
        ref="deptsRef"
        class="filter-tree"
        :data="deptsTreeData"
        node-key="id"
        :props=" {
                  children: 'children',
                  label: 'name'
                }"
        :default-checked-keys="expandedArr"
        :expand-on-click-node="false"
        :render-content="renderContent"
        @node-expand="handleExpand"
        @node-collapse="handleCollapse"
        :filter-node-method="filterNode">
      </el-tree>
    </div>
    <div class="common-tree__foot" v-show="$slots.foot || $scopedSlots.foot">
      <slot
        name="foot"
        :loading="loading"
        :filters="filters"
        :selects="selects"
      ></slot>
    </div>
  </div>
</template>

<script>
import mixin from "../mixin";
import {object, string, int, session,cache} from "../util";
import {getParentIdsByDepts,getDeptsByUserDeptsLocation} from '@/utils/deptUtil'
import {deptApi} from '@/api/dept'
export default {
  name: "comp-depts",
  mixins: [mixin],
  props: {
    select: {type: Boolean, default: false},
    link: {type: Boolean, default: false},
    datalist: {type: String},
    filterValue:{type: String},
    filterParams:{type:  Object}
  },
  data: () => ({
    loading: false,
    deptF: "",
    filters: {

      linage: 20000,
      page: 1,
      total: 0,
    },
    list: [],
    selects: [],
    deptsTreeData: [],
    activeId:'',
    expandedArrTemp:[], // 默认展开的节点
    expandedArr:[], // 默认展开的节点
  }),
  methods: {
    // 子组件内部定义的自定义事件
    triggerCustomEvent(dept) {
      //   this.search();

      console.log("dept", dept);
      this.$emit("custom-event", "一些数据");
    },

    reset(deep) {
      this.expandedArr = this.expandedArrTemp
      let data = deep
        ? {}
        : object(
          session([
            this.env.key,
            this.$options.name,
            "filters",
            this.$route.fullPath,
          ])
        );
      this.filters = Object.assign(this.$options.data().filters, data);
      this.search(true);
    },
    validate() {
      let filters = this.filters;
      filters.total = Math.max(int(filters.total), 0);
      filters.linage = Math.max(int(filters.linage), 1);
      filters.page = Math.max(
        Math.min(int(filters.page), Math.ceil(filters.total / filters.linage)),
        1
      );
      session(
        [this.env.key, this.$options.name, "filters", this.$route.fullPath],
        filters
      );
    },
    search(clean) {
      if (this.loading) return;
      if (clean) this.list = [];
      if (clean) this.selects = [];
      let filters = this.filters;
      this.validate();
      this.loading = true;
      const deptsTreeData = cache('deptsTreeData')
      if(deptsTreeData && !clean){
        this.deptsTreeData = deptsTreeData
        this.loading = false;
      }else{
        deptApi.getDeptsSimpleList(this.profile.depments?.[0]?.dept?.city?.id).then((res) => {
          this.loading = false;
          this.list = [];
          this.selects = [];
          if (res.code === 0) {
            let data = res.data.map(x=>{
              return {
                ...x,
                id: x.deptId,
                name: x.deptName,
                parentId: x.parentId || ''
              }
            })
            filters.total = 0;
            this.list = data
            // this.list = data.sort((a, b) => {
            //   let [a1, a2, a3] = [a.city.id, a.county.id, a.sort];
            //   let [b1, b2, b3] = [b.city.id, b.county.id, b.sort];
            //   return a1 === b1 ? (a2 === b2 ? b3 - a3 : a2 - b2) : a1 - b1;
            // });
            console.log(" this.list", this.list.filter(x=>x.name=='政府部门'));
            this.validate();

            this.dealListToTree()

            // this.deptsTreeData = this.plugins.treeData.arrayToTree(this.list, 'id', 'parentId', '')
            // cache('deptsTreeData',this.deptsTreeData)
          } else {
            filters.total = 0;
            this.deptsTreeData = []
            this.validate();
            this.plugins.modal.toast(
              "列表加载失败<br>" + res.code + "：" + res.msg,
              "error"
            );
          }
          this.$emit("update-data");
        });
      }

    },
    /**
     * 最小化刷新列表，根据提供的ids刷新这几个单位的信息就行了，其它的部门没有更新和新增就不用刷新了
     * 只能用在更新上
     * @param ids id,id2,id3
     */
    miniUpdateList(ids){
      if(ids){
        this.loading = true
        this.plugins.user.getDepts({
          ...this.filters,
          deptIds:ids
        }).then(res=>{
          this.loading = false
          if(res.code == 0){
            if(res.data.list.length>0){
              const idsNewList = res.data.list.map(x=>x.id)
              this.list.forEach(x=>{
                if(idsNewList.includes(x.id)){
                  x = res.data.list.find(y=>x.id==y.id)
                }
              })
            }
          }
          this.dealListToTree()
        }).finally(()=>{
          this.loading = false
        })
      }
    },
    dealListToTree(){
      // this.list.forEach(dept=>{
      //   dept.dept.name = this.list.find(x=>x.id==dept.dept.id)?.name
      // })

      // 获取归属地相同的部门
      // const depts = getDeptsByUserDeptsLocation(this.list, this.profile.depments)
      const depts = this.list
      console.log('depts', depts)
      // administrator看完所有的
      if (this.profile.number == 'administrator') {
        this.deptsTreeData = this.plugins.treeData.arrayToTree(this.list, 'id', 'parentId', '')
      } else {
        // 从相同归属地的部门中找到所有归属地的父节点ID
        let parentIds = getParentIdsByDepts(depts)

        console.log('parentIds', parentIds)
        this.deptsTreeData = []
        parentIds.forEach((parentId) => {
          if (parentId) {
            const dept = depts.find(x => x.id == parentId)
            this.deptsTreeData.push({
              ...dept,
              children: this.plugins.treeData.arrayToTree(this.list, 'id', 'parentId', parentId)
            })
          } else {
            // 本来就是顶层的 parentId = ""
            this.deptsTreeData = this.deptsTreeData.concat(this.plugins.treeData.arrayToTree(this.list, 'id', 'parentId', ''))
          }
        })
      }
      cache('deptsTreeData',this.deptsTreeData)
    },
    activateDept(dept) {
      dept.activated = !dept.activated;
    },
    activateDeptMouseenter(dept) {
      dept.activated = true;
    },
    activateDeptMouseleave(dept) {
      dept.activated = false;
    },
    expandDept(dept) {
      this.deptF = dept;

      if (dept.expanded) {
        dept.expanded = false;
      } else if (dept.loaded) {
        dept.expanded = true;
      } else {
        this.loading = true;
        this.plugins.user
          .getDepts({deptId: dept.id, linage: 1000, page: 1})
          .then((res) => {
            this.loading = false;
            if (res.code === 0) {
              dept.depts = res.data.list;

              dept.depts.forEach((item) => {
                item.dept.name = dept.name;
                item.level = dept.level + 1;
              });
              dept.depts.sort((a, b) => {
                let [a1, a2, a3] = [a.city.id, a.county.id, a.sort];
                let [b1, b2, b3] = [b.city.id, b.county.id, b.sort];
                return a1 === b1 ? (a2 === b2 ? b3 - a3 : a2 - b2) : a1 - b1;
              });
              dept.expanded = true;
              dept.loaded = true;
            } else {
              this.plugins.modal.toast(
                "加载失败<br>" + res.code + "：" + res.msg,
                "error"
              );
            }
          });
      }
    },
    selectDept(dept) {
      console.log(dept);
      let select = (depts, selects) =>
        depts.reduce((selects, dept) => {
          if (dept.selected) selects.push(dept);
          return select(dept.depts, selects);
        }, selects);
      if (this.select) {
        dept.selected = !dept.selected;
        this.selects = select(this.list, []);
      } else {
        this.selects = [];
        this.expandDept(dept);
      }
    },
    filterDept(){
      console.log('this.filterParams', this.filterParams)
      console.log('this.filterValue', this.filterValue)
      this.$refs.deptsRef.filter(this.filterParams.name || this.filterValue || '')

    },
    filterNode(value, data,node) {
      if (!value && this.filterParams?.belongToIdArr?.length == 0) {
        return true;
      }
      return value?data.name.includes(value):false || this.filterParams?.belongToIdArr?.includes(data.belongToId);
    },
    renderContent(h, {node, data, store}) {
      return h('div',{class: 'custom-tree-node',
        style:'display:flex;width:100%;padding:4px;align-items:center',
        on:{
          mouseleave:()=>{
            console.log('mouseleave', node.data.id)
            const els = window.document.getElementsByClassName(node.data.id)
            els[els.length - 1].className = node.data.id+' button-null'
          },
          mouseenter:()=>{
            const els = window.document.getElementsByClassName(node.data.id)
            els[els.length - 1].className = ''+node.data.id
          }
        }
      },[
        h('div', {style: 'width:66%'}, node.label),
        h('div', {style: 'float:right',class:node.data.id+' button-null'}, this.$scopedSlots.body({
          data: node.data
        }))
      ])
    },
    init() {
      this.loading = false;
      this.reset();
      console.log(this.datalist, 111);
    },
    handleExpand(data,node,e){
      this.expandedArrTemp.push(data.id)
      console.log(this.expandedArrTemp)
    },
    handleCollapse(data,node,e){
      this.expandedArrTemp = this.expandedArrTemp.filter(id=>id!==data.id)
      console.log(this.expandedArrTemp)
    }
  },
};
</script>

<style lang="scss">
.comp-depts {
  overflow: hidden;
}
</style>
<style>
.el-tree-node__content{
    height: 36px !important;
}
.button-null{
    display: none;
}
</style>
